package com.tzx.fluttermixedapplication.viewmodel

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.tzx.base.base.BaseViewModel
import com.tzx.fluttermixedapplication.beans.ResultOneDayEnglishData
import com.tzx.fluttermixedapplication.net.api.OioApiServiceImpl
import com.tzx.fluttermixedapplication.net.api.VVHApiServiceImpl
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch

class WeatherViewModel : BaseViewModel() {
    private val _weatherCitySharedFlow = MutableSharedFlow<String>()
    val weatherFlow = _weatherCitySharedFlow.asSharedFlow()

    private val _oneDayEnglishSharedFlow = MutableSharedFlow<ResultOneDayEnglishData.OneDayEnglishData>()
    val oneDayEnglishDataFlow = _oneDayEnglishSharedFlow.asSharedFlow()

    fun getWeatherWithCityData(cityName: String) {
        viewModelScope.launch {
            val result = VVHApiServiceImpl.getWeatherWithCity(cityName)
            result.getOrNull()?.let {
                Log.d(
                    "tanzhenxing",
                    "${Thread.currentThread().name}:getWeatherWithCityData:${it}"
                )
                val sb = StringBuilder()
                sb.append(it.city)
                    .append('\n')
                    .append("日期:${it.data.date}\n")
                    .append("周:${it.data.week}\n")
                    .append("天气:${it.data.type}\n")
                    .append("气温:${it.data.high}~${it.data.low}\n")
                    .append("风：${it.data.fengxiang} ${it.data.fengli}\n")
                _weatherCitySharedFlow.emit(sb.toString())
            } ?: kotlin.run {
                result.exceptionOrNull()?.printStackTrace()
            }
        }
    }

    fun getOneDayEnglish() {
        viewModelScope.launch {
            val result = OioApiServiceImpl.getOneDayEnglish()
            result.getOrNull()?.result?.let {
                Log.d(
                    "tanzhenxing",
                    "${Thread.currentThread().name}:getOneDayEnglish:${it}"
                )
                _oneDayEnglishSharedFlow.emit(it)
            } ?: kotlin.run {
                result.exceptionOrNull()?.printStackTrace()
            }
        }
    }
}